package com.foreknow.controller;

import com.foreknow.model.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 服务器端向客户端响应的内容类型（MIME）
        //resp.setContentType("text/html;charset=utf-8");
        // 设置客户端向服务器端发送请求的编码格式
        //req.setCharacterEncoding("utf-8");
        //2. 在浏览器页面中输出内容
        PrintWriter out = resp.getWriter();
        //3. 获取请求的参数 例如：?username=tom&password=123456
        //String getParameter(String name) 以字符串形式返回请求参数的值，或者如果参数不存在则返回 null。
        // <input type="text" id="inputEmail" name="username" class="form-control" placeholder="Email address" required autofocus>
        String username = req.getParameter("username");
        //<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
        String password = req.getParameter("password");
        //out.println(username+"---------"+password);
        //获取HttpSession对象
        HttpSession session = req.getSession();
        //调用业务层service的方法
        AdminService service = new AdminServiceImpl();
        Admin admin = service.isValidate(username,password);
        //可以将用户的信息保存到session中
        session.setAttribute("username",admin.getUsername());
        if(admin != null) {
            req.getRequestDispatcher("manager?q=list").forward(req,resp);
            //resp.sendRedirect("manager?q=list");
        }else {
            out.println("login error......");
        }
    }
}
